import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
import { login, getUserInfo, getUserDetailById } from '@/api/user'

const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken (state, token) {
    state.token = token
    setToken(token)
  },
  removeToken (state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login (context, data) {
    const token = await login(data)

    context.commit('setToken', token)

    setTimeStamp()
  },
  async getUserInfo (context) {
    const info = await getUserInfo()
    const result = await getUserDetailById(info.userId)

    const userInfo = {...info, ...result }

    context.commit('setUserInfo', userInfo)

    return userInfo
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

